import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Select,
  Button,
  Modal,
  Divider, message, Input,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import DescView from './descView';
import styles from '../UserManage.less';
import * as options from '../../../common/options';
import { powerBtnFunc } from '@/utils/utils';
import CompensatoryComponent from './compensatory';

const FormItem = Form.Item;
const confirm = Modal.confirm;

/* eslint react/no-multi-comp:0 */
@connect(({ compensatory, loading }) => ({
  compensatory,
  loading: loading.models.compensatory,
}))

@Form.create()
class compensatoryComponent extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    lookDescView: false,
    type: 'compensatory',
    selectedRows: {},
    formValues: {},
    value: '',
    pagination: {
      pageNo: 1,
      pageSize: 15,
    },
  };

  columns = [
    {
      title: '还款编号',
      key: 'repaymentNo',
      dataIndex: 'repaymentNo',
    },
    {
      title: '企业名称',
      dataIndex: 'enterpriseName',
      key: 'enterpriseName',
    },
    {
      title: '标的名称',
      key: 'projectName',
      dataIndex: 'projectName',
    },
    {
      title: '还款日期',
      key: 'repayTime',
      dataIndex: 'repayTime',
    },
    {
      title: '回款日期',
      key: 'backTime',
      dataIndex: 'backTime',
    },
    {
      title: '账单金额',
      key: 'amount',
      dataIndex: 'amount',
    },
    {
      title: '本金',
      key: 'principal',
      dataIndex: 'principal',
    },
    {
      title: '利息',
      dataIndex: 'interest',
      key: 'interest',
    },
    {
      title: '服务费',
      key: 'fee',
      dataIndex: 'fee',
    },
    {
      title: '状态',
      render: val => <span>
        {val.overdueStatus === 1 ? options.compensatoryStatus0.map(item => (item.key === val.compensatoryStatus ? item.value : '')) : options.compensatoryStatus.map(item => (item.key === val.compensatoryStatus ? item.value : ''))}
        </span>,
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          {
            powerBtnFunc('100151',
              [<a
                onClick={() => this.handleRecharge(record)}>充值</a>,
                <Divider type="vertical"/>])
          }
          {
            record.compensatoryStatus !== 4 && record.compensatoryStatus !== 5 ?
              powerBtnFunc('100150',
                [<a
                  onClick={() => this.handleModalVisible(true, record)}>确认代偿</a>,
                  <Divider type="vertical"/>]) : ''
          }
          {
            powerBtnFunc('100149',
              <a onClick={() => this.handleLookDesc(true, record)}>查看</a>,
            )}
        </Fragment>
      ),
    },
  ];

  constructor(props) {
    super(props);
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'compensatory/fetch',
    });
  }

  handleModalVisible = (flag, record = []) => {
    this.setState({
      type: 'compensatory',
      selectedRows: record,
      modalVisible: flag,
    });
  };
  handleRepay = (row) => {
    let _this = this;
    const { dispatch } = this.props;
    const { selectedRows } = this.state;
    dispatch({
      type: 'compensatory/confirm',
      payload: {
        repaymentNo: selectedRows.repaymentNo,
        ...row,
      },
      callback: (res) => {
        _this.setState({
          modalVisible: false,
        });
        window.open(res.url);
      },
    });

  };
  handleRecharge = (row) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'compensatory/recharge',
      payload: {
        repaymentNo: row.repaymentNo,
        amount: row.amount.indexOf(',') !== -1 ? row.amount.replace(',', '') : Number(row.amount),
      },
      callback: (res) => {
        if (res.code === 200) {
          console.log(res);
          window.open(res.msg.url);
        } else {
          message.error(res.errMsg);
        }
      },
    });
  };
  handleStandardTableChange = (pagination) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;


    this.setState({
      pagination: {
        pageNo: pagination.current,
        pageSize: 15,
      },
    });
    const params = {
      pageNo: pagination.current,
      pageSize: 15,
      ...formValues,
    };

    dispatch({
      type: 'compensatory/fetch',
      payload: params,
    });
  };
  //重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'compensatory/fetch',
      payload: {},
    });
  };


  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };
  //搜索
  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
      };
      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'compensatory/fetch',
        payload: values,
      });
    });
  };
  //修改
  handleUpdateModalVisible = (flag, record) => {
    const { dispatch } = this.props;
    confirm({
      title: '请确认?',
      content: '请再次确认是否放款！！',
      onOk() {
        dispatch({
          type: 'compensatory/confirm',
          payload: { code: record.loanNo },
        });
      },
      onCancel() {
      },
    });

  };
  //查看
  handleLookDesc = (flag, record) => {
    const { dispatch } = this.props;
    this.setState({
      lookDescView: !!flag,
      selectedRows: record,
    }, () => {
      if (!!flag) {
        dispatch({
          type: 'compensatory/detail',
          payload: { code: record.repaymentNo },
        });
      }
    });

  };
  handleUpTop = (fieldsValue) => {

    const { dispatch } = this.props;
    let _this = this;
    dispatch({
      type: 'compensatory/recharge',
      payload: {
        ...fieldsValue,
      },
      callback: (res) => {
        if (res.code === 200) {
          console.log(res);
          window.open(res.msg.url);
          _this.setState({
            modalVisible: false,
          });
        } else {
          message.error(res.errMsg);
        }
      },
    });

  };
  uptop = (flag, record) => {

    this.setState({
      type: 'uptop',
      selectedRows: record,
      modalVisible: flag,
    });


  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <div>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={12} sm={24}>
            <Form onSubmit={this.handleSearch} layout="inline">
              <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                <Col md={14} sm={24}>
                  <FormItem label="代偿状态">
                    {getFieldDecorator('status')(
                      <Select placeholder="请选择" style={{ width: '100%' }}>
                        {options.compensatoryStatus.map((item) => {
                          return <Select.Option value={item.key} key={item.key}>{item.value}</Select.Option>;
                        })}
                      </Select>,
                    )}
                  </FormItem>
                </Col>
                <Col md={10} sm={24}>
        <span className={styles.submitButtons}>
        <Button type="primary" htmlType="submit">
        查询
        </Button>
        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
        重置
        </Button>
          <Button style={{ marginLeft: 8 }} type="primary" onClick={() => this.uptop(true, [])}>充值</Button>

        </span>
                </Col>
              </Row>
            </Form>
          </Col>

        </Row>


      </div>
    );
  }


  render() {
    const { compensatory: { data, details }, loading } = this.props;
    const { selectedRows, lookDescView, modalVisible, type } = this.state;
    const compensatoryProps = {
      modalVisible: modalVisible,
      type: type,
      handleRepay: this.handleRepay,
      handleUpTop: this.handleUpTop,
      handleModalVisible: this.handleModalVisible,
    };

    return (
      <PageHeaderWrapper title="代偿管理">
        <Card bordered={false}>

          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>

            {data ?
              <StandardTable
                selectedRows={selectedRows}
                loading={loading}
                data={data}
                rowKey='loanNo'
                rowSelectHide={true}
                columns={this.columns}
                onSelectRow={this.handleSelectRows}
                onChange={this.handleStandardTableChange}
              /> : ''}
          </div>
        </Card>
        {details ?
          <DescView handleLookDesc={this.handleLookDesc} selectedRows={details} lookDescView={lookDescView}/>
          : ''
        }
        <CompensatoryComponent {...compensatoryProps}/>
      </PageHeaderWrapper>
    );
  }
}

export default compensatoryComponent;
